package com.letoken.platform.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.letoken.platform.app.job.SharingCirculationRewardsJbo;
import com.letoken.platform.app.service.AppUserIssueService;
import com.letoken.platform.app.service.AppUserTeamService;
import com.letoken.platform.app.service.QuickSwapService;
import com.letoken.platform.pub.annotation.auth.NotAuthorization;
import com.letoken.platform.pub.enums.LetokenTokenTypeEnum;
import com.letoken.platform.pub.enums.TokenTransactionStatusEnum;
import com.letoken.platform.pub.enums.TokenTransactionTypeEnum;
import com.letoken.platform.pub.res.ApiResponse;
import com.letoken.platform.pub.util.LocalEnvUtils;
import com.letoken.platform.repo.admin.dao.AdminIssueConfigMapper;
import com.letoken.platform.repo.admin.dao.AppUserSwapRecordMapper;
import com.letoken.platform.repo.app.dao.*;
import com.letoken.platform.repo.app.po.AdminFundLevelConfig;
import com.letoken.platform.repo.app.po.AppFundLevelInfo;
import com.letoken.platform.repo.app.po.AppUserAssetsHistory;
import com.letoken.platform.repo.app.po.AppUserWallet;
import com.letoken.platform.repo.utlis.LocalBlockUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/test")
@Api(tags = "我的-系统公告", description = "系统公告接口")
public class TestController {
    @Autowired
    private AppUserIssueService appUserIssueService;
    @Resource
    private AppUserIssueMapper appUserIssueMapper;
    @Resource
    private AdminIssueConfigMapper adminIssueConfigMapper;

    @Autowired
    private AppUserTeamService appUserTeamService;
    @Autowired
    private QuickSwapService quickSwapService;
    @Resource
    private AppUserMapper appUserMapper;
    @Autowired
    private SharingCirculationRewardsJbo sharedSharingCirculationRewardsJbo;
    @Autowired
    private AppUserSwapRecordMapper swapRecordMapper;

    @GetMapping("/hello")
    @ApiOperation(value = "hello", notes = "hello")
    @NotAuthorization
    public ApiResponse<String> hello() {
        return ApiResponse.create("hello");
    }

    @GetMapping("/hello_user")
    @ApiOperation(value = "hello_user", notes = "hello_user")
    public ApiResponse<String> helloUser() {
        return ApiResponse.create("hello_user");
    }
    @NotAuthorization
    @GetMapping("/wallet")
    public ApiResponse<String> wallet() {
        if (LocalEnvUtils.isDev() || LocalEnvUtils.isDebug()){
            return ApiResponse.create(LocalBlockUtils.obtainUserId(LocalBlockUtils.ObtainUserIdDto.builder().coinId(1)
                    .sysId(1)
                    .addr("0x1Efc9eDB13236134e6aea52aAD860bF32D3064f4")
                    .build()));
        }
        return ApiResponse.create("no ok");
    }
//    @GetMapping("/ceshi")
//    @ApiOperation(value = "查询闪兑配置", notes = "查询闪兑配置")
//    @NotAuthorization
//    public ApiResponse<QuerySwapConfigRes> queryQuickSwapConfig() {
//        appUserIssueService.sharingCirculationRewards(2,new BigDecimal("0.02"),2,10080);
//        return ApiResponse.create(null);
//    }

//    @PostMapping("/upload")
//    @ApiOperation("绑定")
//    @NotAuthorization
//    public ApiResponse<String> upload(@RequestParam String code,@RequestParam Integer userid)  {
//       /* AppBindInvitationCodeReq aa = new AppBindInvitationCodeReq();
//        aa.setInvitationCode(code);
//        aa.setToken(appUserMapper.selectById(userid).getToken());
//        aa.setId(userid);
//        appUserTeamService.bindInvitationCode(aa);*/
//        return null;
//    }
//    @PostMapping("/mint")
//    @ApiOperation("铸币")
//    @NotAuthorization
//    public ApiResponse<String> mint(@RequestParam String tokenId)  {
//        /*AppUserMintLetReq AppUserMintLetReq = new AppUserMintLetReq();
//        AppUserMintLetReq.setMintAmount(new BigDecimal("10000"));
//        AppUserMintLetReq.setToken(appUserMapper.selectById(10000213).getToken());
//        AppUserMintLetReq.setId(10000213);
//        quickSwapService.MintLet(AppUserMintLetReq);




//        AppUserMintLetReq AppUserMintLetReq1 = new AppUserMintLetReq();
//        AppUserMintLetReq1.setMintAmount(new BigDecimal("10000"));
//        AppUserMintLetReq1.setToken(appUserMapper.selectById(10000214).getToken());
//        AppUserMintLetReq1.setId(10000214);
//        quickSwapService.MintLet(AppUserMintLetReq1);
//
//        AppUserMintLetReq AppUserMintLetReq2 = new AppUserMintLetReq();
//        AppUserMintLetReq2.setMintAmount(new BigDecimal("20000"));
//        AppUserMintLetReq2.setToken(appUserMapper.selectById(10000215).getToken());
//        AppUserMintLetReq2.setId(10000215);
//        quickSwapService.MintLet(AppUserMintLetReq2);
//
//        AppUserMintLetReq AppUserMintLetReq3 = new AppUserMintLetReq();
//        AppUserMintLetReq3.setMintAmount(new BigDecimal("30000"));
//        AppUserMintLetReq3.setToken(appUserMapper.selectById(10000216).getToken());
//        AppUserMintLetReq3.setId(10000216);
//        quickSwapService.MintLet(AppUserMintLetReq3);
//
//        AppUserMintLetReq AppUserMintLetReq4 = new AppUserMintLetReq();
//        AppUserMintLetReq4.setMintAmount(new BigDecimal("40000"));
//        AppUserMintLetReq4.setToken(appUserMapper.selectById(10000217).getToken());
//        AppUserMintLetReq4.setId(10000217);
//        quickSwapService.MintLet(AppUserMintLetReq4);
//
//
//        AppUserMintLetReq AppUserMintLetReq5 = new AppUserMintLetReq();
//        AppUserMintLetReq5.setMintAmount(new BigDecimal("10000"));
//        AppUserMintLetReq5.setToken(appUserMapper.selectById(10000218).getToken());
//        AppUserMintLetReq5.setId(10000218);
//        quickSwapService.MintLet(AppUserMintLetReq5);
//
//
//        AppUserMintLetReq AppUserMintLetReq6 = new AppUserMintLetReq();
//        AppUserMintLetReq6.setMintAmount(new BigDecimal("10000"));
//        AppUserMintLetReq6.setToken(appUserMapper.selectById(10000219).getToken());
//        AppUserMintLetReq6.setId(10000219);
//        quickSwapService.MintLet(AppUserMintLetReq6);
//
//
//        AppUserMintLetReq AppUserMintLetReq7 = new AppUserMintLetReq();
//        AppUserMintLetReq7.setMintAmount(new BigDecimal("10000"));
//        AppUserMintLetReq7.setToken(appUserMapper.selectById(10000220).getToken());
//        AppUserMintLetReq7.setId(10000220);
//        quickSwapService.MintLet(AppUserMintLetReq7);
//
//
//        AppUserMintLetReq AppUserMintLetReq8 = new AppUserMintLetReq();
//        AppUserMintLetReq8.setMintAmount(new BigDecimal("60000"));
//        AppUserMintLetReq8.setToken(appUserMapper.selectById(10000221).getToken());
//        AppUserMintLetReq8.setId(10000221);
//        quickSwapService.MintLet(AppUserMintLetReq8);
//
//
//        AppUserMintLetReq AppUserMintLetReq9 = new AppUserMintLetReq();
//        AppUserMintLetReq9.setMintAmount(new BigDecimal("20000"));
//        AppUserMintLetReq9.setToken(appUserMapper.selectById(10000222).getToken());
//        AppUserMintLetReq9.setId(10000222);
//        quickSwapService.MintLet(AppUserMintLetReq9);
//
//
//
//        AppUserMintLetReq AppUserMintLetReq10 = new AppUserMintLetReq();
//        AppUserMintLetReq10.setMintAmount(new BigDecimal("30000"));
//        AppUserMintLetReq10.setToken(appUserMapper.selectById(10000223).getToken());
//        AppUserMintLetReq10.setId(10000223);
//        quickSwapService.MintLet(AppUserMintLetReq10);
//
//
//        AppUserMintLetReq AppUserMintLetReq11 = new AppUserMintLetReq();
//        AppUserMintLetReq11.setMintAmount(new BigDecimal("40000"));
//        AppUserMintLetReq11.setToken(appUserMapper.selectById(10000224).getToken());
//        AppUserMintLetReq11.setId(10000224);
//        quickSwapService.MintLet(AppUserMintLetReq11);
//
//        AppUserMintLetReq AppUserMintLetReq12 = new AppUserMintLetReq();
//        AppUserMintLetReq12.setMintAmount(new BigDecimal("10000"));
//        AppUserMintLetReq12.setToken(appUserMapper.selectById(10000225).getToken());
//        AppUserMintLetReq12.setId(10000225);
//        quickSwapService.MintLet(AppUserMintLetReq12);
//
//        AppUserMintLetReq AppUserMintLetReq13 = new AppUserMintLetReq();
//        AppUserMintLetReq13.setMintAmount(new BigDecimal("10000"));
//        AppUserMintLetReq13.setToken(appUserMapper.selectById(10000226).getToken());
//        AppUserMintLetReq13.setId(10000226);
//        quickSwapService.MintLet(AppUserMintLetReq13);
//
//        AppUserMintLetReq AppUserMintLetReq14 = new AppUserMintLetReq();
//        AppUserMintLetReq14.setMintAmount(new BigDecimal("50000"));
//        AppUserMintLetReq14.setToken(appUserMapper.selectById(10000227).getToken());
//        AppUserMintLetReq14.setId(10000227);
//        quickSwapService.MintLet(AppUserMintLetReq14);
//
//        AppUserMintLetReq AppUserMintLetReq15 = new AppUserMintLetReq();
//        AppUserMintLetReq15.setMintAmount(new BigDecimal("30000"));
//        AppUserMintLetReq15.setToken(appUserMapper.selectById(10000228).getToken());
//        AppUserMintLetReq15.setId(10000228);
//        quickSwapService.MintLet(AppUserMintLetReq15);
//        AppUserMintLetReq AppUserMintLetReq16 = new AppUserMintLetReq();
//        AppUserMintLetReq16.setMintAmount(new BigDecimal("10000"));
//        AppUserMintLetReq16.setToken(appUserMapper.selectById(10000229).getToken());
//        AppUserMintLetReq16.setId(10000229);
//        quickSwapService.MintLet(AppUserMintLetReq16);*/
//        return null;
//    }

//    @PostMapping("/reward")
//    @ApiOperation("job")
//    @NotAuthorization
//    public ApiResponse reward(){
//        sharedSharingCirculationRewardsJbo.reward();
//        return ApiResponse.create(null);
//    }

//    @Resource
//    private AppUserManager appUserManager;

//    @Autowired
//    private AppUserAddressManager appUserAddressManager;
//
//    @Resource
//    private AppUserAddressManager addressManager;

//    @Resource
//    private FaUserMapper faUserMapper;
//
//    @Autowired
//    private AppUserWalletService appUserWalletService;
    

//    @PostMapping("/test")
//    @ApiOperation("初始化数据")
//    @NotAuthorization
//    public ApiResponse test(){
//        List<FaUser> faUsers = faUserMapper.getUserList();
//        if(faUsers.size()>0){
//            AppUser appUser = appUserManager.queryByWalletAddres(faUsers.get(0).getUsername());
//            if(appUser != null){
//                return ApiResponse.create("操作完成");
//            }
//        }
//        for (FaUser faUser:faUsers) {
//            AppUserLoginReq req = new AppUserLoginReq();
//            req.setWalletAddress(faUser.getUsername());
//            this.login(req);
//        }
//        List<FaUser> faUsers2 =  faUserMapper.getUserListParentname();
//        for (FaUser faUser:faUsers2) {
//            AppUser appUser = appUserManager.queryByWalletAddres(faUser.getParentname());
//            AppBindInvitationCodeReq req = new AppBindInvitationCodeReq();
//            req.setInvitationCode(appUser.getInvitationCode());
//            faUser.setEmail(appUser.getInvitationCode());
//            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~"+faUser.getUsername());
//            appUserTeamService.bindInvitationTest(faUser);
//        }
//        return ApiResponse.create("操作完成");
//    }


//    public AppUserLoginRes login(AppUserLoginReq req) {
//        //todo 去掉了验证 AppUserSession,只验证了redis里的token
//       // log.info("login params [AppUserLoginReq={}, clientIP={}]", JSON.toJSONString(req), clientIP);
//        String walletAddress = req.getWalletAddress();
//
//        AppUserLoginRes res = new AppUserLoginRes();
//
//        //先校验钱包地址的合法性
//        /*boolean check = false;
//        if (LetokenBlockchainEnum.BSC.getValue().equalsIgnoreCase(blockchain)) {
//            //ETH公链验签
//            check = SignUtil.recoverSignature(message, sign, walletAddress);
//        }
//        if (!check) {
//            log.info("login check signature verification failed");
//            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_APP_USER_003);
//        }*/
//        AppUser appUser = appUserManager.queryByWalletAddres(walletAddress);
//        String token = TokenUtil.generateToken();
//        if (ObjectUtils.isEmpty(appUser)) {
//            appUser = new AppUser();
//            //用户信息为空，创建用户并绑定
//            appUser.setWalletAddress(walletAddress);
//            //给钱包分配地址
//            AppUserAddress wallet = null;
//            try {
//                wallet = appUserAddressManager.createWallet();
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }

//
//            appUser.setAddressId(wallet.getId());
//            appUser.setInviterId(0);
//            appUser.setInvitationCode(RandomUtil.getRandomNum());
//            appUser.setToken(token);
//            appUser.setCreateTime(LocalDateTime.now());
//            Integer flag = appUserManager.addUser(appUser);
//            if (flag > 0) {
//                appUser.setUserName(LetokenUserConstant.USER_ID_PREFIX + appUser.getId());
//                appUser.updateById();
//                wallet.setUserId(appUser.getId());
//                wallet.updateById();
//                LocalDateTime now = LocalDateTime.now();
////                BigDecimal zero = new BigDecimal("0");
//                //将用户的平台钱包地址缓存到redis
//                AppWalletAddresRedis.me().put(String.valueOf(appUser.getId()), wallet.getWalletAddress());
//                AppUserTeam appUserTeam = new AppUserTeam();
//                appUserTeam.setUserId(appUser.getId());
//                appUserTeam.setEcoLevel(0);
//                appUserTeam.setEcoValue(BigDecimal.ZERO);
//                appUserTeam.setUserValue(BigDecimal.ZERO);
//                appUserTeam.setTeamMember(0);
//                appUserTeam.setTeamValue(0);
//                appUserTeam.setUserAchievement(0);
//                appUserTeam.setInviterId(0);
//                appUserTeam.setCreateTime(now);
//                appUserTeam.setUpdateTime(now);
//                appUserTeam.setTeamSumValue(0);
//                appUserTeam.insert();
//

//                AppUserTeamPath appUserTeamPath = new AppUserTeamPath();
//                appUserTeamPath.setUserId(appUser.getId());
//                appUserTeamPath.setInvitePath("");
//                appUserTeamPath.insert();
//
//
//                // 新增到资产表里
//                AppUserWallet letWallet = new AppUserWallet();
//                letWallet.setUserId(appUser.getId());
//                letWallet.setTokenId(LetokenTokenTypeEnum.LET.getId());
//                letWallet.setAvailableBalance(BigDecimal.ZERO);
//                letWallet.setFreezeBalance(BigDecimal.ZERO);
//                letWallet.setReleasedBalance(BigDecimal.ZERO);
//                letWallet.setUpdateTime(now);
//                letWallet.setCreateTime(now);
//
//                AppUserWallet usdtWallet = new AppUserWallet();
//                usdtWallet.setUserId(appUser.getId());
//                usdtWallet.setTokenId(LetokenTokenTypeEnum.USDT.getId());
//                usdtWallet.setAvailableBalance(BigDecimal.ZERO);
//                usdtWallet.setFreezeBalance(BigDecimal.ZERO);
//                usdtWallet.setReleasedBalance(BigDecimal.ZERO);
//                usdtWallet.setUpdateTime(now);
//                usdtWallet.setCreateTime(now);
//                List<AppUserWallet> walletList = new ArrayList<>();
//                walletList.add(letWallet);
//                walletList.add(usdtWallet);
//                appUserWalletService.saveBatch(walletList);
//
//            }
//        }
//        //判断token是否存在缓存中，若存在，则踢出
//        String queryToken = appUser.getToken();
//        if (StringUtils.isNotBlank(queryToken)) {
//            AppLoginTokenRedis.me().del(queryToken);
//        }
//        appUser.setToken(token);
//        AppLoginTokenRedis.me().put(token, appUser);
////        //再创建用户session
////        AppUserSession appUserSession = this.registerUserSession(appUser, req, clientIP);
//        //记录登陆日志
////        appUserLoginLogAsync.insertAppUserLoginLog(appUserSession);
//        //更新用户最后一次登录时间
//        appUserManager.updateById(appUser);
//        res.setToken(token);
//        String address = addressManager.queryWalletByUserId(appUser.getId());
//        res.setAppUserAddress(address);
//       // log.info("login return [ userName={}, userLoginPhoneSms={}]", JSON.toJSONString(res));
//        return res;
//    }



//    @PostMapping("/appUserLog")
//    @ApiOperation("定时将用户登录日志写库")
//    @NotAuthorization
//    public ApiResponse appUserLog(){
//        appUserLoginLogJob.appUserLoginLog();
//        return ApiResponse.create();
//    }
//    @PostMapping("/swapTest")
//    @ApiOperation("app_user_swap_record 迁移 app_user_assets_history")
//    @NotAuthorization
//    public void swapRecordToAssetsHistory(){
//        List<AppUserSwapRecord> appUserSwapRecords = swapRecordMapper.selectList(null);
//        for (AppUserSwapRecord appUserSwapRecord : appUserSwapRecords) {
//            AppUserAssetsHistory assetHistory = new AppUserAssetsHistory();
//            Integer swapType = null;
//            if (appUserSwapRecord.getFromType().equals(LetokenTokenTypeEnum.USDT.getId())){
//                swapType = TokenTransactionTypeEnum.USDT_LET.getValue();
//            }else{
//                swapType = TokenTransactionTypeEnum.LET_USDT.getValue();
//            }
//            assetHistory.setUserId(appUserSwapRecord.getUserId());
//            assetHistory.setType(swapType);
//            assetHistory.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
//            assetHistory.setTokenId(LetokenTokenTypeEnum.USDT.getId());
//            if (swapType.equals(TokenTransactionTypeEnum.USDT_LET.getValue())){
//                assetHistory.setAmount(appUserSwapRecord.getFromAmount().negate());
//            }else {
//                assetHistory.setAmount(appUserSwapRecord.getToAmount());
//            }
//            assetHistory.setSn(appUserSwapRecord.getOrderId());
//            assetHistory.setCreateTime(appUserSwapRecord.getCreateTime());
//            assetHistory.setUpdateTime(LocalDateTime.now());
//            assetHistory.insert();
//            assetHistory.setId(null);
//            assetHistory.setTokenId(LetokenTokenTypeEnum.LET.getId());
//            assetHistory.setCreateTime(appUserSwapRecord.getCreateTime());
//            assetHistory.setUpdateTime(LocalDateTime.now());
//            if (swapType.equals(TokenTransactionTypeEnum.USDT_LET.getValue())){
//                assetHistory.setAmount(appUserSwapRecord.getToAmount());
//            }else {
//                assetHistory.setAmount(appUserSwapRecord.getFromAmount().negate());
//            }

//            assetHistory.insert();
//        }

//    }

    @Resource
    AppFundLevelInfoMapper appFundLevelInfoMapper;
    @Resource
    private AdminFundLevelConfigMapper adminFundLevelConfigMapper;
    @NotAuthorization
    @GetMapping("/updateFundLevelJob")
    public  void UpdateDateLet(){
        List<Integer> list = appFundLevelInfoMapper.getUserList();
        for (Integer userId:list) {
            updateLevel(userId);
        }
    }
    private void updateLevel(Integer inviterId ){
        AppFundLevelInfo info = appFundLevelInfoMapper.selectById(inviterId);
        List<AdminFundLevelConfig> levelConfigs = adminFundLevelConfigMapper.getLevelList();
        if(info==null || info.getLevel()<levelConfigs.size()){
            Integer count = appFundLevelInfoMapper.getFundByInviterIdCOunt(inviterId);
            Integer count2 = appFundLevelInfoMapper.getFundByUserId(inviterId);
            if(count2>0){
                for (AdminFundLevelConfig adminFundLevelConfig:levelConfigs) {
                    if (count >= adminFundLevelConfig.getCondition()){
                        AppFundLevelInfo appFundLevelInfo = new AppFundLevelInfo();
                        appFundLevelInfo.setLevel(adminFundLevelConfig.getLevel());
                        appFundLevelInfo.setUserId(inviterId);
                        appFundLevelInfo.setUpdateTime(LocalDateTime.now());
                        appFundLevelInfo.insertOrUpdate();
                        break;
                    }
                }
            } else {
                AppFundLevelInfo appFundLevelInfo = new AppFundLevelInfo();
                appFundLevelInfo.setLevel(0);
                appFundLevelInfo.setUserId(inviterId);
                appFundLevelInfo.insertOrUpdate();
            }
        }
    }
    @Resource
    private AppUserWalletMapper appUserWalletMapper;

    @Autowired
    AppUserAssetsHistoryMapper appUserAssetsHistoryMapper;

    //@NotAuthorization
   // @GetMapping("/LPDividend")
    public  void LPDividend() {
        List<AppUserWallet> walletList = appUserWalletMapper.getLPAmount();
        for (AppUserWallet appUserWallet:walletList) {
            BigDecimal money = appUserWallet.getAvailableBalance().multiply(new BigDecimal("0.00241"));
            Integer walletId = appUserWalletMapper.checkoutTokenIdAndUserId(LetokenTokenTypeEnum.CAP.getId(), appUserWallet.getUserId());
            AppUserWallet w = appUserWalletMapper.selectForUpdate(walletId);
            AppUserWallet updateW = new AppUserWallet();
            updateW.setId(w.getId());
            updateW.setAvailableBalance(w.getAvailableBalance().add(money));
            appUserWalletMapper.updateById(updateW);

            AppUserAssetsHistory assetHistory = new AppUserAssetsHistory();
            assetHistory.setUserId(appUserWallet.getUserId());
            assetHistory.setType(TokenTransactionTypeEnum.LP_Dividend.getValue());
            assetHistory.setStatus(TokenTransactionStatusEnum.COMPLETED.getValue());
            assetHistory.setTokenId(LetokenTokenTypeEnum.CAP.getId());
            assetHistory.setAmount(money);
            assetHistory.setBalance(updateW.getAvailableBalance());
            assetHistory.setCreateTime(LocalDateTime.now());
            assetHistory.setUpdateTime(assetHistory.getCreateTime());
            appUserAssetsHistoryMapper.insert(assetHistory);
        }
    }

}
